/**
 * 商品管理
 */

//导入相应的库
import express from 'express';

//导入数据库连接
import conn from './../db/db'

import config from '../src/config';
import {basename} from 'path';
import formidable from 'formidable'
import { isGeneratorFunction } from 'util/types';
/**
 * 
 * 商品分类
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodsCategory(req, res){
    let sqlStr = 'SELECT * FROM category';
  conn.query(sqlStr, (error, results, fields) => {
      if (error) {
          res.json({err_code: 0, message: '请求商品分类数据失败'});
          console.log(error);
      } else {
          results = JSON.parse(JSON.stringify(results));
          res.json({success_code: 200, message: results});
      }
  });
}

/**
 * 搜索商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodsSearchgoods(req, res){
   // 获取参数
   let keywords = req.body.keywords;
   keywords = keywords.replace(/\s+/g, ' ');
   keywords = keywords.replace(/(^\s*)|(\s*$)/g, '');
     let keyArr = keywords.split(' ');
     let sqlStr = 'SELECT * FROM recommend WHERE goods_name LIKE ';  // sql语句
     keyArr.forEach((item, index, arr)=>{
         sqlStr += "'%" + item + "%'";
         if(index != arr.length-1){
             sqlStr += " OR goods_name LIKE ";
         }
     });
     conn.query(sqlStr, (error, results, fields) => {
         results = JSON.parse(JSON.stringify(results));
         if (!error && results.length) {
             res.json({success_code: 200, message: results});
         }else{
             console.log(error);
         }
     });
}

/**
 * 推荐列表
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodsreCommendshoplist(req,res){
     // 获取参数
     let category = req.query.category
     let pageNo = req.query.pageNo    
     let pageSize = req.query.count   
     if(req.query.category=="NaN"){
        category=1
     }
     if(req.query.pageNo=="NaN"){
        pageNo=1
     }
     if(req.query.pageSize=="NaN"){
        pageSize=3
     }
     
  let sqlStr = 'SELECT * FROM recommend WHERE category = ' + category + ' LIMIT ' + (pageNo - 1) * pageSize + ',' + pageSize;

  conn.query(sqlStr, (error, results, fields) => {
      if (error) {
    console.log(error);
          res.json({err_code: 0, message: '请求商品列表数据失败'});
      } else {
          results = JSON.parse(JSON.stringify(results));
          res.json({success_code: 200, message: results});
      }
  });
}

/**
 * 获取所有商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodsAllgoods(req,res){
    let sqlStr = 'SELECT * FROM recommend';

    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
			console.log(error);
            res.json({err_code: 0, message: '请求商品数据失败'});
        } else {
            results = JSON.parse(JSON.stringify(results));
            res.json({success_code: 200, message: results});
        }
    });
}

/**
 * 获取首页商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodsHomeshoplist(req,res){
        // 获取总分类
        let cateSqlStr = 'SELECT COUNT(*) FROM category';
        conn.query(cateSqlStr, (error, results, fields) => {
          if (!error) {
                  let sqlStr = '';
                  for(let i=0; i < results[0]['COUNT(*)']; i++){
                      sqlStr += 'SELECT * FROM recommend WHERE category = ' + (i+1) + ' LIMIT 3;';
                  }
                  conn.query(sqlStr, (error, results, fields) => {
                      if (!error) {
                          results = JSON.parse(JSON.stringify(results));
                          res.json({success_code: 200, message: results});
                      }
                  });
          }
        });
}

/**
 * 获取首页商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodsdetail(req,res){
     // 获取参数
     let goodsNo = req.query.goodsNo;
     let sqlStr = 'SELECT * FROM recommend WHERE goods_id = ' + goodsNo;
     conn.query(sqlStr, (error, results, fields) => {
       if (!error) {
               results = JSON.parse(JSON.stringify(results));
         res.json({success_code: 200, message: results});
       }
     });
}

/**
 * 获取商品评价
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function goodscomment(req,res){
     // 获取参数
     let goodsId = req.query.goodsId;

     let sqlStr = 'SELECT user_info.id, user_info.user_name, user_info.user_nickname, comments.comment_detail, comments.comment_id, comments.comment_rating, comments.goods_id FROM user_info INNER JOIN comments ON user_info.id = comments.user_id WHERE goods_id = ' + goodsId;
     conn.query(sqlStr, (error, results, fields) => {
       if (!error) {
               results = JSON.parse(JSON.stringify(results));
         res.json({success_code: 200, message: results});
       }
     });
}

/**
 * 评论商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function postcomment(req,res){
    // 获取参数
	let goods_id = req.body.goods_id;
	let comment_detail = req.body.comment_detail;
	let comment_rating = req.body.comment_rating;
	let user_id = req.body.user_id;
    const addSql = "INSERT INTO comments(goods_id, comment_detail, comment_rating, user_id) VALUES (?, ?, ?, ?)";
    const addSqlParams = [goods_id, comment_detail, comment_rating, user_id];
    conn.query(addSql, addSqlParams, (error, results, fields) => {
        results = JSON.parse(JSON.stringify(results));
        if (!error) {
          // 更新数据
          let sqlStr = "UPDATE recommend SET comments_count = comments_count + 1 WHERE goods_id = " + goods_id;
          conn.query(sqlStr, (error, results, fields) => {
            if (error) {
              console.log(error);
            } else {
              res.json({success_code: 200, message: "发布成功"});
            }
          });
        }
     });
}

/**
 * 修改商品数量
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function changeGoodsCount(req,res){
     // 获取数据
     const goods_id = req.body.goods_id;
     const buy_count = req.body.count;
   const user_id = req.body.user_id;
 
     let sqlStr = "UPDATE cart SET buy_count = ? WHERE goods_id = " + goods_id + " AND user_id = " + user_id;
     let strParams = [buy_count];
     conn.query(sqlStr, strParams, (error, results, fields) => {
         if (error) {
       console.log(error);
             res.json({err_code: 0, message: '修改商品数量失败!'});
         } else {
             res.json({success_code: 200, message: '修改商品数量成功!'});
         }
     });
}

/**
 * 删除recommend单条商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function deleteRecomGoods(req,res){
    // 获取数据
    const goods_id = req.body.goods_id;
	
    let sqlStr = "DELETE FROM recommend WHERE goods_id =" + goods_id;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
			console.log(error);
            res.json({err_code: 0, message: '删除失败!'});
        } else {
			let sqlStr2 = "DELETE FROM cart WHERE goods_id =" + goods_id;
			conn.query(sqlStr, (error, results, fields) => {
				if (error) {
					console.log(error);
					res.json({err_code: 0, message: '删除失败!'});
				} else {
					res.json({success_code: 200, message: '删除成功!'});
				}
			});
        }
    });
}

/**
 * 修改recommend商品信息
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function updateRecomGoods(req,res){
    // 获取数据
    const goods_id = req.body.goods_id;
    const goods_name = req.body.goods_name;
    const short_name = req.body.short_name;
    const price = req.body.price;
    const counts = req.body.counts;
    const category = req.body.category;

    let sqlStr = "UPDATE recommend SET goods_name = ?, short_name = ?, price = ?, counts = ?, category = ? WHERE goods_id = " + goods_id;
    let strParams = [goods_name, short_name, price, counts, category];
    conn.query(sqlStr, strParams, (error, results, fields) => {
        if (error) {
			console.log(error);
            res.json({err_code: 0, message: '修改失败!'});
        } else {
            res.json({success_code: 200, message: '修改成功!'});
        }
    });
}


/**
 * 添加商品到recommend
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function addShopRecom(req,res){
    // 获取客户端传过来的商品信息
	const form = new formidable.IncomingForm();
  form.uploadDir = config.uploadsGoodsPath;  // 上传图片放置的文件夹
  form.keepExtensions = true; // 保持文件的原始扩展名
  form.parse(req, (err, fields, files)=>{
      if(err){
          return next(err);
      }
  let goods_id = fields.goods_id;
  let goods_name = fields.goods_name;
  let short_name = fields.short_name;
  let price = fields.price;
  let normal_price = price + 300;
  let market_price = price + 500;
  let sales_tip = fields.sales_tip;
  let category = fields.category;
  let comments_count = 0;
  let counts = fields.counts;
  let thumb_url = 'http://localhost:' + config.port + '/uploads/' + basename(files.goods_img.path);
  let image_url = 'http://localhost:' + config.port + '/uploads/' + basename(files.goods_img.path);
  let hd_thumb_url = 'http://localhost:' + config.port + '/uploads/' + basename(files.goods_img.path);
  
  let sql_str = "SELECT * FROM recommend WHERE goods_id = " + goods_id;
  conn.query(sql_str, (error, results, fields) => {
    if (error) {
      res.json({err_code: 0, message: '服务器内部错误!'});
    } else {
      results = JSON.parse(JSON.stringify(results));
      if (results[0]) { // 商品已经存在
        res.json({success_code: 500, message: '该商品已在数据库中'});
      } else { // 商品不存在
        let add_sql = "INSERT INTO recommend(goods_id, goods_name, short_name, thumb_url, image_url, hd_thumb_url, price, normal_price, market_price, sales_tip, category, counts, comments_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        let sql_params = [goods_id, goods_name, short_name, thumb_url, image_url, hd_thumb_url, price, normal_price, market_price, sales_tip, category, counts, comments_count];
        conn.query(add_sql, sql_params, (error, results, fields) => {
          if (error) {
            console.log(error);
            res.json({err_code: 0, message: '加入失败!'});
          } else {
            let sqlStr = "UPDATE category SET cate_counts = cate_counts + 1  WHERE cate_id = " + category;
            conn.query(sqlStr, [], (error, results, fields) => {
              if (error) {
                console.log(error);
              } else {
                res.json({success_code: 200, message: '加入成功!'});
              }
            });
          }
        });
      }
    }
  });
});
}

/**
 * 添加商品到recommend
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function deleteAllGoods(req,res){
	const user_id = req.body.user_id;
	
  let sqlStr = "DELETE FROM cart WHERE user_id = " + user_id;
  conn.query(sqlStr, (error, results, fields) => {
      if (error) {
    console.log(error);
          res.json({err_code: 0, message: '删除失败!'});
      } else {
          res.json({success_code: 200, message: '删除成功!'});
      }
  });
}

/**
 * 删除购物车单条商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function deleteGoods(req,res){
     // 获取数据
     const goods_id = req.body.goods_id;
     const user_id = req.body.user_id;
     
       let sqlStr = "DELETE FROM cart WHERE goods_id =" + goods_id + " AND user_id = " + user_id;
       conn.query(sqlStr, (error, results, fields) => {
           if (error) {
         console.log(error);
               res.json({err_code: 0, message: '删除失败!'});
           } else {
               res.json({success_code: 200, message: '删除成功!'});
           }
       });
}

/**
 * 查询购物车的商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function cartGoods(req,res){
     // 获取参数
     let user_id = req.query.user_id;
     let sqlStr = "SELECT * FROM cart WHERE user_id =" + user_id;
     conn.query(sqlStr, (error, results, fields) => {
         if (error) {
       console.log(error);
             res.json({err_code: 0, message: '请求购物车商品数据失败'});
         } else {
             res.json({success_code: 200, message: results});
         }
     });
}

/**
 * 添加购物车的商品
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function addShopCart(req,res){
        // 验证用户
        let user_id = req.body.user_id;
        if(!user_id){
            res.json({err_code:0, message:'非法用户'});
            return;
        }
        // 获取客户端传过来的商品信息
        let goods_id = req.body.goods_id;
        let goods_name = req.body.goods_name;
        let thumb_url = req.body.thumb_url;
        let price = req.body.price;
        let buy_count = req.body.buy_count;
        let is_pay = 0; // 0 未购买 1购买
	      let counts = req.body.counts;

        let sql_str = "SELECT * FROM cart WHERE goods_id = " + goods_id + " AND user_id=" + user_id + " LIMIT 1";
        conn.query(sql_str, (error, results, fields) => {
            if (error) {
                res.json({err_code: 0, message: '服务器内部错误!'});
            } else {
                results = JSON.parse(JSON.stringify(results));
                if (results[0]) { // 商品已经存在
                    res.json({success_code: 200, message: '该商品已在购物车中'});
                } else { // 商品不存在
		    		let add_sql = "INSERT INTO cart(goods_id, goods_name, thumb_url, price, buy_count, is_pay, user_id, counts) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
		    		let sql_params = [goods_id, goods_name, thumb_url, price, buy_count, is_pay, user_id, counts];
		    		conn.query(add_sql, sql_params, (error, results, fields) => {
		    			if (error) {
                            res.json({err_code: 0, message: '加入购物车失败!'});
                            console.log(error);
		    			} else {
		    				res.json({success_code: 200, message: '加入购物车成功!'});
		    			}
		    		});
                }
            }
        });
}





export default {
  goodsCategory,
  goodsSearchgoods,
  goodsreCommendshoplist,
  goodsAllgoods,
  goodsHomeshoplist,
  goodsdetail,
  goodscomment,
  postcomment,
  changeGoodsCount,
  deleteRecomGoods,
  updateRecomGoods,
  addShopRecom,
  deleteAllGoods,
  deleteGoods,
  cartGoods,
  addShopCart

}